package ui;

import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import util.CapsJdbc;
import util.CapsRes;
import util.CapsTableView;

import java.net.URL;
import java.util.*;

public class LessonMgr implements Initializable {

   @FXML
   private TextField lno;

   @FXML
   private TextField name;
   
   @FXML
   private TextField plno;

   @FXML
   private TextField credit;
   
   @FXML
   private TextField lessonCond;

   @FXML
   private TableView<Map<String,String>> lessonTv;

   @FXML
   private void saveLesson(ActionEvent event) {
      List<Object> params = new ArrayList<>(Arrays.asList(name.getText(),plno.getText(),credit.getText(),lno.getText()));
      String updSql = "update lesson set name=?,plno=?,credit=? where lno=?";
      CapsRes capsRes = CapsJdbc.execSQL(updSql,params);
      if (capsRes.getTtlNum() < 1) {
         String addSql = "insert into lesson(name,plno,credit,lno) values(?,?,?,?)";
         CapsJdbc.execSQL(addSql,params);
      }
      this.qryByLesson(null);
   }
   
   @FXML
   private void qryByLesson(ActionEvent event) {
      this.dealQry(lessonCond.getText());
   }

   @Override
   public void initialize(URL url, ResourceBundle rb) {
//      deptTv.getSelectionModel().selectedItemProperty()
//              .addListener((observable,  oldValue, newValue) -> {
//
////                 System.out.println("observable:"+observable.getValue()+";oldValue:"+oldValue
////                         +";newValue:"+newValue);
//              });
      this.dealQry(null);
   }

   private void dealQry(String lessonName) {
      String strSQL = "select lno,name,plno,credit from lesson";
      List<Object> params = null;
      if (null != lessonName && lessonName.length() > 0) {
         strSQL += " where name like ?";
         params = new ArrayList<>(1);
         params.add(lessonName+"%");
      }
      CapsRes capsRes = CapsJdbc.execSQL(strSQL,params);
      CapsTableView.dealTableView(capsRes,lessonTv);
      CapsTableView.addButtonToTable(lessonTv,(recMap,idCol) -> {
         String delSql = "delete from lesson where lno = ?";
         List<Object> delParams = new ArrayList<>(1);
         delParams.add(recMap.get("lno"));
         CapsJdbc.execSQL(delSql,delParams);
         this.dealQry(null);
      },(recMap,idCol) -> {
           lno.setText(recMap.get("lno"));
           name.setText(recMap.get("name"));
           plno.setText(recMap.get("plno"));
           credit.setText(recMap.get("credit"));
      });
   }
}

